from goods.models import GoodsCategory,GoodsChannel

def get_category():
    # 0,分类数据存储器
    categories = {}

    # 1,查询一级分类（商品频道）,根据group_id排序，组内再根据sequence排序
    channels = GoodsChannel.objects.order_by("group_id", "sequence")

    # 2,遍历所有的商品频道（目的：分成11个组）
    for channel in channels:
        # 2,1 判断频道的group_id是否已经添加到存储器中了
        if channel.group_id not in categories:
            categories[channel.group_id] = {
                "channels": [],
                "sub_cats": []
            }
        # 2,2 在存储器中添加一级分类
        cat1_dict = {
            "id": channel.id,
            "name": channel.category.name,
            "url": channel.url
        }
        categories[channel.group_id]["channels"].append(cat1_dict)

        # 2,3 二级分类
        for cat2 in channel.category.subs.all():
            cat2_dict = {
                "name": cat2.name,
                "subs": []
            }

            # 2,4 三级分类
            for cat3 in cat2.subs.all():
                cat3_dict = {
                    "name": cat3.name,
                    "id": cat3.id
                }
                # 将三级分类添加到二级分类中
                cat2_dict["subs"].append(cat3_dict)

            # 2,5 将二级分类再添加到数据存储器中
            categories[channel.group_id]["sub_cats"].append(cat2_dict)

    return categories
